﻿// Insperation from http://msdn.microsoft.com/en-us/library/dd254918(v=xnagamestudio.31).aspx 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Santa_sAdventure.Model
{
    class AnimationPlayer
    {
        private float m_timeElapsed;
        private int m_frameIndex;

        // The current animation playing
        internal Animation CurrentAnimation { get; set; }

        internal AnimationPlayer(Animation a_idleAnimation)
        {
            CurrentAnimation = a_idleAnimation;
        }

        // Play animation
        internal void PlayAnimation(Animation a_animation)
        {
            // Check if current animation is already playing
            if (CurrentAnimation != a_animation)
            {
                CurrentAnimation = a_animation;
                m_timeElapsed = 0;
                m_frameIndex = 0;
            }
        }

        /// Origin position
        public Vector2 Origin
        {
            get { return new Vector2(0, 0); }
        }

        // Draw animation
        internal void DrawAndUpdate(float timeElapsed, SpriteBatch spriteBatch, Rectangle position, SpriteEffects spriteEffects)
        {
            // Process passing time.
            m_timeElapsed += timeElapsed;
            while (m_timeElapsed > CurrentAnimation.FrameTime)
            {
                m_timeElapsed -= CurrentAnimation.FrameTime;

                // Advance the frame index; looping or clamping as appropriate.
                if (CurrentAnimation.IsLooping)
                {
                    m_frameIndex = (m_frameIndex + 1) % CurrentAnimation.NumberOfFrames;
                }
                else
                {
                    m_frameIndex = Math.Min(m_frameIndex + 1, CurrentAnimation.NumberOfFrames - 1);
                }
            }

            // Calculate the source rectangle of the current frame.
            Rectangle source = new Rectangle(m_frameIndex * CurrentAnimation.Texture.Height, 0, CurrentAnimation.Texture.Height, CurrentAnimation.Texture.Height); 

            // Draw the current frame.
            spriteBatch.Draw(CurrentAnimation.Texture, position, source, Color.White, 0.0f, Origin, spriteEffects, 0.0f);
        }
    }
}
